﻿angular.module('Caltech')
.controller('customerEquipmentItemController', function ($scope, Restangular, $stateParams, $q, moment, $state) {
    'use strict';

    var defaultModel = {
        equipment: {
        }
    };

    if ($stateParams.id) {
        Restangular.one('customerEquipment', $stateParams.id).get().then(function (data) {
            $scope.model = data;
        });
    } else {
        $scope.model = {
            customer: {
                name: $stateParams.customerName,
                id: $stateParams.customerId
            },
            equipment: {
            },
            calibrationDate: new Date(),
            nextDueDate: moment().add('years', 1).toDate()
        };
    }

    $scope.update = function (model) {
        model.equipmentId = model.equipment.id;
        model.customerId = model.customer.id;
        model.equipment = undefined;
        return model.put().then(function () {
            $state.forceReload();
        });
    };

    $scope.save = function (model) {
        model.equipmentId = model.equipment.id;
        model.customerId = model.customer.id;
        model.equipment = undefined;
        return Restangular.all('customerEquipment').post(model).then(function (id) {
            $state.go('customerEquipment-item', { id: id });
        });
    };

    $scope.remove = function (model) {
        return model.remove().then(function () {
            history.back();
        });
    };

    $scope.getEquipmentList = function (model) {
        return Restangular.all('equipment').getList({
            model: model
        });
    };

    $scope.updateEquipmentItem = function (equipment) {
        if (!equipment) {
            $scope.model.equipment = {};
        } else if (typeof (equipment) === 'object') {                
            $scope.model.equipment = equipment;
            $scope.model.price = equipment.price;
        }
    };
});